package ar.uba.fi.taller2.ftrs.query;
import java.util.Iterator;
import java.util.ArrayList;


class Tboolexp {
  Texp exp1, exp2;             
  String  kind;               

  public Tboolexp(Texp e1, String k, Texp e2) {
    exp1=e1;
    kind=k;
    exp2=e2;
  }

  public Tboolexp(String k, Texp e1) {
    exp1=e1;
    exp2=null;
    kind=k; 
  }

  public String toString() {
    if (kind.equals("NOT"))
      return(kind+" "+exp1);
    else 
      return(exp1+" "+kind+" "+exp2);
  }

  private ArrayList applyAND(ArrayList A, ArrayList B){	
	Iterator i = A.iterator();
	 while(i.hasNext()){
		 Object o= i.next();
		 if (! B.contains(o)){
			 A.remove(o);
		 }
	 }	 
	 return A;
  }
  
 private ArrayList applyOR(ArrayList A, ArrayList B){	 
	 Iterator i = A.iterator();
	 while(i.hasNext()){
		 Object o= i.next();
		 if (! B.contains(o)){
			 B.add(o);
		 }
	 }	 
	 return B;
  }
  
 private ArrayList applyNOT(ArrayList A){
	 ArrayList B = Tindex.getDocumentList(); 
	 Iterator i = A.iterator();
	 while(i.hasNext()){
		 Object o= i.next();
		 if (! B.contains(o)){
			 B.remove(o);
		 }
	 }	 
	 return B;
 } 
 
 private ArrayList getList(String S){
	 return new ArrayList();
 }
 
  public ArrayList interpret() {    
	ArrayList l1=new ArrayList();
	ArrayList l2=new ArrayList();
	if ( exp1 != null ){
       l1 = exp1.interpret();
    }
    if ( exp2 != null){
       l2 = exp2.interpret();
    }
    if ( exp1 != null && exp2 != null)
       {
         if (kind.equals("OR")){          
            return(applyOR(l1, l2));
         }
         if (kind.equals("AND")){            
            return(applyAND(l1,l2));
         }            
       }
    
    if ( exp1 != null && exp2 == null)
       return(applyNOT(l1));     
    
    return new ArrayList();
  }
}

